package com.roarkry.styloid;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class styloid extends Activity {
	
	//TODO: Rename / refactor member variables and methods
	
	private static final int CAMERA_PIC_REQUEST = 4;  
	private StyloidDbAdapter mDb;
	private int currentColor;
	private int currentArticle;
	private int redCount;
	private int blueCount;
	private int greenCount;
	
    //Applications "Main" method
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentColor = -1;
        currentArticle = 1;
        mDb = new StyloidDbAdapter(this);
        mDb.open();
        setContentView(R.layout.main);
    }
    
    //http://www.tutorialforandroid.com/2009/01/displaying-alertdialog-in-android.html
    public void launchColorPicker(final View v){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.create();
        alertDialog.setCursor(mDb.fetchAllColors(), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                currentColor = which+1;//give it a 1 offset because the table id doesn't match the list id
                
                //TODO: CLEAN UP
                Cursor c = mDb.fetchColor(currentColor);
                String rgb = c.getString(c.getColumnIndex(StyloidDbAdapter.KEY_COLOR_RGB));
                fillImageView(R.id.interpretedColor, Color.parseColor("#"+rgb));
                
                TextView topText = (TextView) findViewById(R.id.topText);
                topText.setText("Current Color = " + currentColor);
                TextView colorText = (TextView) findViewById(R.id.interpretedColorText);
    	   		colorText.setText("(" + mDb.getColorName(rgb) + ")");
                c.close();
            	
                return;
            } }, StyloidDbAdapter.KEY_COLOR_TITLE);
        alertDialog.show();
    	//new ColorPicker(this).show();
    }
    
    //http://www.tutorialforandroid.com/2009/01/displaying-alertdialog-in-android.html
    public void launchArticlePicker(final View v){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.create();
        alertDialog.setCursor(mDb.fetchAllAticles(), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	currentArticle = which+1;
            	
            	//TODO: CLEAN UP
            	
                return;
            } }, StyloidDbAdapter.KEY_COLOR_TITLE);
        alertDialog.show();
    	//new ColorPicker(this).show();
    }
    
    //check if this instance is running inside of emulator
    public boolean isEmulator() {
    	String id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
    	boolean emulator = TextUtils.isEmpty(id);
    	if (!emulator) {
    	emulator = id.toUpperCase().equals("9774D56D682E549C");
    	}
    	return emulator;
    }
    
    //Launches the camera activity
    public void launchCamera(View v){
    	if(!isEmulator()){
    		Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
    		startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  
    	}
    	else{ //emulator won't run camera - so pretend.
    		TextView topText = (TextView) findViewById(R.id.topText);
            topText.setText("Current Color = emulator (#404040)");
            redCount = 150;
            blueCount = 150;
            greenCount = 150;
            
            fillImageView(R.id.capturedColor, Color.parseColor("#" + getColor()));
            
            String interpreted = mDb.interpretColor(getColor());
            fillImageView(R.id.interpretedColor, Color.parseColor("#"+interpreted));
	   		TextView colorText = (TextView) findViewById(R.id.interpretedColorText);
	   		colorText.setText("(" + mDb.getColorName(interpreted) + ")");
    	}
    }
    
    //Activity Results get sent here
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    	if (requestCode == CAMERA_PIC_REQUEST) {  
    		if (resultCode == RESULT_OK) { 
    			Bitmap thumbnail = (Bitmap) data.getExtras().get("data");  
				ImageView imageView = (ImageView) findViewById(R.id.previewImageView);
				imageView.setImageBitmap(thumbnail);
				
				setColor(thumbnail);
				
				TextView topText = (TextView) findViewById(R.id.topText);
				topText.setText("Current Color = " + getColor());
				
				fillImageView(R.id.capturedColor, Color.parseColor("#"+getColor()));
				String interpreted = mDb.interpretColor(getColor());
				fillImageView(R.id.interpretedColor, Color.parseColor("#"+interpreted));
				TextView colorText = (TextView) findViewById(R.id.interpretedColorText);
				colorText.setText("(" + mDb.getColorName(interpreted) + ")");
    		}
    		else{
    			Toast.makeText(this, "Picture Not Taken", Toast.LENGTH_SHORT).show();
    		}
    	}
    } 
    
    //grab the average color in the middle section of the photo
    private void setColor(Bitmap image){
    	redCount = 0;
    	blueCount = 0;
    	greenCount = 0;
    	
    	int height, width, currentPixel;
    	height = image.getHeight();
    	width  = image.getWidth();
    	
    	height/=3;
    	width/=3;
    	int pixels = height*width;
    	
    	for(int h = 0; h < height; h++){
    		for(int w = 0; w < width; w++){
    			currentPixel = image.getPixel(w+width, h+height);
    			redCount += Color.red(currentPixel);
    			blueCount += Color.blue(currentPixel);
    			greenCount += Color.green(currentPixel);
    		}
    	}
    	
    	redCount /= pixels;
    	blueCount /= pixels;
    	greenCount /= pixels;
    }
    
    //takes the current color data and returns a string
    private String getColor(){
    	return Integer.toHexString(redCount) + Integer.toHexString(greenCount) + Integer.toHexString(blueCount);
    }

    //fill the ImageView with this id with a specific color
    //TODO: Make templates of clothing - all white, and fill in for the appropriate color (instead of a square of color)
    private void fillImageView(int id, int color){
    	
    	int article = currentArticle;
    	
    	//get the name of the template / article
    	String bmpName = mDb.getArticleName(article).toLowerCase();
    	
    	//open up two bitmaps: the article/template and a new one to display to the user
    	int height = 40;
    	int width = 30;
    	Bitmap bm = null;
    	Bitmap x = null;
		try{
			InputStream ins = this.getAssets().open(bmpName+".bmp");
			x = BitmapFactory.decodeStream(ins);
			height = x.getHeight();
			width = x.getWidth();
		}
		catch (Exception ex){
			
		}
		bm = Bitmap.createBitmap(width, height, Config.RGB_565);

    	//fill in a new bitmap based off the imported one from assets (template)
        for(int i = 0; i < width; i++){
        	for(int j = 0; j < height; j++){
        		if(x.getPixel(i, j) == Color.WHITE)
        			bm.setPixel(i, j, color);
        		else
        			bm.setPixel(i, j, x.getPixel(i, j));
        	}
        }
        
        ImageView toFill = (ImageView) findViewById(id);
        toFill.setImageBitmap(bm);
    }
}